﻿using Microsoft.AspNetCore.Mvc.Filters;
using System.Reflection;

namespace Bright.NetCore.Api.Filter
{
    // 自定义过滤器
    public class DefaultValueFilter : IActionFilter
    {
        public void OnActionExecuting(ActionExecutingContext context)
        {
            foreach (var argument in context.ActionArguments)
            {
                var parameterName = argument.Key;
                var parameterValue = argument.Value;

                // 获取当前参数在接口方法定义中的元数据
                var parameterInfo = context.ActionDescriptor.Parameters.FirstOrDefault(p => p.Name == parameterName);

                if (parameterInfo != null)
                {
                    var targetType = parameterInfo.ParameterType;

                    // 如果参数值为 null 或者类型不匹配，尝试创建新实例
                    if (parameterValue == null || !targetType.IsInstanceOfType(parameterValue))
                    {
                        try
                        {
                            var newInstance = Activator.CreateInstance(targetType);
                            context.ActionArguments[parameterName] = newInstance;
                            parameterValue = newInstance;
                        }
                        catch (Exception ex)
                        {
                            // 处理创建实例时可能出现的异常
                            Console.WriteLine($"Failed to create instance of type {targetType.FullName}: {ex.Message}");
                        }
                    }

                    // 设置默认值
                    if (parameterValue != null)
                    {
                        SetDefaultValues(parameterValue);
                    }
                }
            }
        }

        private void SetDefaultValues(object obj)
        {
            var properties = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
            foreach (var property in properties)
            {
                if (property.PropertyType.IsClass && property.GetValue(obj) == null)
                {
                    try
                    {
                        var instance = Activator.CreateInstance(property.PropertyType);
                        property.SetValue(obj, instance);
                    }
                    catch (Exception ex)
                    {
                        // 处理创建属性实例时可能出现的异常
                        Console.WriteLine($"Failed to create instance of property {property.Name} of type {property.PropertyType.FullName}: {ex.Message}");
                    }
                }
            }
        }

        public void OnActionExecuted(ActionExecutedContext context)
        {
            // 这里可以处理 Action 执行后的逻辑，目前留空
        }
    }
}
